﻿using Aspose.Cells;
using BLL;
using HslCommunication;
using HslCommunication.Profinet.Panasonic;
using Model;
using PLCDataCollector.Core.Entities;
using PLCDataCollector.Core.Interfaces;
using PLCDataCollector.Services;
using PLCDataCollector.Services.Data;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using System.Xml;

namespace MachineStatusClient
{
    public partial class Form1 : Form
    {
        private readonly IDataService _dataService;
        private List<DeviceMapping> _deviceMappings;
        private Dictionary<string, IPLCService> _plcServices;
        private Dictionary<string, Thread> _collectionThreads;
        public Form1()
        {
            InitializeComponent();
            _plcServices = new Dictionary<string, IPLCService>();
            _collectionThreads = new Dictionary<string, Thread>();
            // 读取配置
            var connectionString = ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString.ToString(); ;

            // 创建数据服务实例
            _dataService = new DataService(connectionString);
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            // 测试数据库连接
            if (!_dataService.TestConnection())
            {
                MessageBox.Show("数据库连接失败，请检查连接字符串配置", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            InitializePlcConnections();

        }
        private void InitializePlcConnections()
        {
            try
            {
                // 获取设备映射
                var machineId = ConfigurationManager.AppSettings["MachineId"];
                _deviceMappings = _dataService.GetDeviceMappings(machineId);

                // 创建PLC服务
                foreach (var device in _deviceMappings)
                {
                    var service = PLCServiceFactory.CreatePLCService(device);
                    if (service.Connect())
                    {
                        _plcServices.Add(device.MmachineId, service);

                        var thread = new Thread(() => DeviceDataCollectionWorker(device));
                        thread.Name = $"DataCollection_{device.MachineId}";
                        thread.IsBackground = true;

                        _collectionThreads.Add(device.MachineId, thread);
                        thread.Start();
                        //Log($"成功连接到设备: {device.MachineId}, IP: {device.Ip}");
                    }
                    else
                    {
                        // Log($"连接设备失败: {device.MachineId}, IP: {device.Ip}");
                    }
                }
            }
            catch (Exception ex)
            {
                // 处理异常
            }
        }
        private void DeviceDataCollectionWorker(DeviceMapping device)
        {
            var dataBuffer = new List<PlcDataHistory>();
            var lastSaveTime = DateTime.Now;
            var collectionInterval = 1000;


            var details = _dataService.GetList(device.MmachineId, device.MachineId, 0, 100);
            while (true)
            {
                // 采集设备的所有点位数据
                foreach (var detail in details)
                {
                    try
                    {
                        var result = _plcServices[device.MmachineId].ReadData(detail);
                        if (result.IsSuccess)
                        {
                            var data = new PlcDataHistory
                            {
                                MachineId = device.MachineId,
                                DataAddress = detail.DataAddress,
                                DataName = detail.DataName,
                                DataValue = result.Content.ToString(),
                                DataType = detail.DataType,
                                MMachineId = device.MmachineId,
                                CollectionTime = DateTime.Now
                            };

                            dataBuffer.Add(data);
                            _dataService.BatchSavePlcData(dataBuffer);
                            dataBuffer.Clear();
                            lastSaveTime = DateTime.Now;
                        }
                        else
                        {
                            //  Log($"读取数据失败: {device.MachineId} - {detail.DataName}, 错误: {result.Message}");
                        }
                    }
                    catch (Exception ex)
                    {
                        // Log($"采集数据时发生异常: {device.MachineId} - {detail.DataName}: {ex.Message}");
                    }

                    // 短暂延迟，避免对PLC造成过大压力
                    Thread.Sleep(10);
                }
                // 定期保存数据到数据库
                if (dataBuffer.Count > 0 && (DateTime.Now - lastSaveTime).TotalSeconds >= 5)
                {
                    try
                    {
                        _dataService.BatchSavePlcData(dataBuffer);
                        dataBuffer.Clear();
                        lastSaveTime = DateTime.Now;
                    }
                    catch (Exception ex)
                    {
                        // Log($"批量保存数据失败: {ex.Message}");
                    }
                }

                // 等待下一次采集
                Thread.Sleep(collectionInterval);
            }
        }


        //// 双缓冲面板类
        //private class DoubleBufferedLabel : Panel
        //{
        //    public DoubleBufferedLabel()
        //    {
        //        this.SetStyle(ControlStyles.OptimizedDoubleBuffer |
        //                     ControlStyles.AllPaintingInWmPaint |
        //                     ControlStyles.UserPaint, true);
        //        this.UpdateStyles();
        //    }
        //}
        //private System.Windows.Forms.Timer timer1;
        //private Label lblStatus;
        //private Label lblRunningTime;
        //private Label lblAlarmTime;
        //private Label lblStopTime;
        //BContentToSqlServer bts = new BContentToSqlServer();//写入数据库
        //// 状态枚举
        //private enum DeviceStatus { Running, Alarm, Stop, Error }

        //// 班次枚举
        //private enum ShiftType { DayShift, NightShift, Unknown }
        //// 状态时间累计
        //private TimeSpan runningTime = TimeSpan.Zero;
        //private TimeSpan alarmTime = TimeSpan.Zero;
        //private TimeSpan stopTime = TimeSpan.Zero;

        //// 当前状态和上次更新时间
        //private DeviceStatus currentStatus;
        //private DateTime lastUpdateTime = DateTime.Now;

        //// 新增字段 - 用于当前状态计时
        //private Label lblCurrentStatusDuration;
        //private DateTime currentStatusStartTime = DateTime.Now;

        //// 班次相关变量
        //private ShiftType currentShift = ShiftType.Unknown;
        //private DateTime shiftChangeTime = DateTime.MinValue;
        //private ShiftType previousShift = ShiftType.Unknown;
        //// 点位地址
        ////private string[] deviceAddresses = new string[3]; // 0:运行, 1:报警, 2:停机
        //private string dataAddress = "";
        //// PLC通信对象
        //private PanasonicMewtocolOverTcp plcClient;
        ////private string plcIp = "192.168.150.11";
        //private string plcIp = "192.168.1.11";
        //private int plcPort = 1025;
        //private TableLayoutPanel topPanel;
        //private Panel statusPanel;
        //public Form1()
        //{
        //    InitializeComponent();
        //    if (!HslCommunication.Authorization.SetAuthorizationCode("2fb771c7-4c29-445d-bddd-a7b8a75de397"))
        //    {
        //        Console.WriteLine("active failed");
        //        Console.ReadLine();
        //    }
        //    //EventCenter.StopRequested += OnStopRequested;
        //    // 初始化PLC客户端（实际使用时需配置正确的IP和端口）
        //    plcClient = new PanasonicMewtocolOverTcp(plcIp, plcPort);
        //    // 启用双缓冲
        //    this.SetStyle(ControlStyles.OptimizedDoubleBuffer |
        //                 ControlStyles.AllPaintingInWmPaint |
        //                 ControlStyles.UserPaint, true);
        //    this.UpdateStyles();
        //    //// 使用双缓冲面板作为主容器
        //    //mainPanel = new DoubleBufferedPanel();
        //    //mainPanel.Dock = DockStyle.Fill;
        //    //this.Controls.Add(mainPanel);
        //    // 初始化计时器
        //    timer1 = new System.Windows.Forms.Timer();
        //    timer1.Interval = 1000; // 设置为1秒触发一次
        //    timer1.Tick += timer1_Tick;

        //    InitializeUI();
        //    LoadDeviceAddresses(); // 从XML加载点位地址
        //    LoadShiftConfig(); // 加载班次配置
        //    // 设置窗体全屏
        //    this.WindowState = FormWindowState.Maximized;
        //    //this.FormBorderStyle = FormBorderStyle.None;
        //    timer1.Start();
        //}

        //private void LoadDeviceAddresses()
        //{
        //    try
        //    {
        //        string filePath = "DeviceStatus.xml";
        //        if (!File.Exists(filePath))
        //            throw new FileNotFoundException("状态文件未找到");

        //        XmlDocument doc = new XmlDocument();
        //        doc.Load(filePath);

        //        XmlNode node = doc.SelectSingleNode("/DeviceState/Status");
        //        if (node == null)
        //            throw new Exception("无效的XML格式");

        //        //// 解析逗号分隔的点位地址
        //        //deviceAddresses = node.InnerText.Split(',');

        //        //if (deviceAddresses.Length != 3)
        //        //    throw new Exception("点位配置数量错误，需要3个点位");
        //        dataAddress = node.InnerText;
        //    }
        //    catch (Exception ex)
        //    {
        //        // 初始化失败时使用默认地址
        //        //deviceAddresses = new string[] { "D100", "D102", "D104" };
        //        dataAddress = "D1";
        //        MessageBox.Show($"加载点位配置失败: {ex.Message}\n使用默认地址: D1");
        //    }
        //}

        //// 加载班次配置
        //private void LoadShiftConfig()
        //{
        //    try
        //    {
        //        string filePath = "ShiftConfig.xml";
        //        if (!File.Exists(filePath))
        //            throw new FileNotFoundException("班次配置文件未找到");

        //        XmlDocument doc = new XmlDocument();
        //        doc.Load(filePath);

        //        // 解析班次时间
        //        XmlNode dayStartNode = doc.SelectSingleNode("/Shifts/DayShift/StartTime");
        //        XmlNode dayEndNode = doc.SelectSingleNode("/Shifts/DayShift/EndTime");
        //        XmlNode nightStartNode = doc.SelectSingleNode("/Shifts/NightShift/StartTime");
        //        XmlNode nightEndNode = doc.SelectSingleNode("/Shifts/NightShift/EndTime");

        //        // 这里只是示例，实际使用时需要解析时间并存储
        //        // 班次切换逻辑将在计时器中处理
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show($"加载班次配置失败: {ex.Message}\n将使用默认班次设置");
        //    }
        //}

        //// 检查班次是否发生变化
        //private bool CheckShiftChange()
        //{
        //    // 实际应用中应根据配置的时间判断当前班次
        //    // 这里使用简化逻辑：8:00-20:00为白班，其余为晚班
        //    DateTime now = DateTime.Now;
        //    ShiftType newShift = (now.Hour >= 8 && now.Hour < 20) ? ShiftType.DayShift : ShiftType.NightShift;

        //    if (newShift != currentShift)
        //    {
        //        previousShift = currentShift;
        //        currentShift = newShift;
        //        shiftChangeTime = now;
        //        return true;
        //    }
        //    return false;
        //}

        //// 重置所有时间
        //private void ResetAllTimes()
        //{
        //    runningTime = TimeSpan.Zero;
        //    alarmTime = TimeSpan.Zero;
        //    stopTime = TimeSpan.Zero;
        //    lastUpdateTime = DateTime.Now;
        //}
        //private void InitializeUI()
        //{
        //    this.Text = "设备状态监控";
        //    this.BackColor = Color.LightGray;
        //    this.Resize += MainForm_Resize;

        //    // 主容器 - 使用100%空间
        //    TableLayoutPanel mainLayout = new TableLayoutPanel
        //    {
        //        Dock = DockStyle.Fill,
        //        ColumnCount = 1,
        //        RowCount = 2, // 改回2行
        //        Padding = new Padding(1)
        //    };

        //    // 顶部面板占15%高度
        //    mainLayout.RowStyles.Add(new RowStyle(SizeType.Percent, 15F));
        //    // 状态面板占85%高度
        //    mainLayout.RowStyles.Add(new RowStyle(SizeType.Percent, 85F));

        //    // 顶部面板 - 保持不变
        //    topPanel = new TableLayoutPanel
        //    {
        //        Dock = DockStyle.Fill,
        //        ColumnCount = 3,
        //        RowCount = 1,
        //        ColumnStyles = {
        //        new ColumnStyle(SizeType.Percent, 33.33F),
        //        new ColumnStyle(SizeType.Percent, 33.33F),
        //        new ColumnStyle(SizeType.Percent, 33.33F)
        //    },
        //        Margin = new Padding(0)
        //    };

        //    lblRunningTime = CreateTimeLabel("运行时长: 00:00:00");
        //    lblStopTime = CreateTimeLabel("停机时长: 00:00:00");
        //    lblAlarmTime = CreateTimeLabel("报警时长: 00:00:00");

        //    topPanel.Controls.Add(lblRunningTime, 0, 0);
        //    topPanel.Controls.Add(lblStopTime, 1, 0);
        //    topPanel.Controls.Add(lblAlarmTime, 2, 0);

        //    // 状态面板 - 改为垂直布局
        //    TableLayoutPanel statusLayout = new TableLayoutPanel
        //    {
        //        Dock = DockStyle.Fill,
        //        ColumnCount = 1,
        //        RowCount = 2,
        //        BackColor = Color.Transparent
        //    };

        //    // 状态标签占据70%空间，使其上移
        //    statusLayout.RowStyles.Add(new RowStyle(SizeType.Percent, 50F));
        //    // 持续时间标签占据30%空间
        //    statusLayout.RowStyles.Add(new RowStyle(SizeType.Percent, 50F));

        //    lblStatus = new Label
        //    {
        //        Dock = DockStyle.Fill,
        //        TextAlign = ContentAlignment.BottomCenter, // 底部对齐使文本上移
        //        Text = "当前状态：初始化中...",
        //        AutoSize = false,
        //        Padding = new Padding(4)
        //    };

        //    // 新增：状态持续时间标签
        //    lblCurrentStatusDuration = new Label
        //    {
        //        Dock = DockStyle.Fill,
        //        TextAlign = ContentAlignment.TopCenter, // 顶部对齐
        //        Text = "00:00:00",
        //        AutoSize = false
        //    };
        //    // 使用自定义双缓冲标签
        //    //lblStatus = new DoubleBufferedLabel
        //    //{
        //    //    Dock = DockStyle.Fill,
        //    //    TextAlign = ContentAlignment.BottomCenter,
        //    //    Text = "当前状态：初始化中...",
        //    //    AutoSize = false,
        //    //    Padding = new Padding(4)
        //    //};

        //    //lblCurrentStatusDuration = new DoubleBufferedLabel
        //    //{
        //    //    Dock = DockStyle.Fill,
        //    //    TextAlign = ContentAlignment.MiddleCenter,
        //    //    Text = "00:00:00",
        //    //    AutoSize = false
        //    //};
        //    statusLayout.Controls.Add(lblStatus, 0, 0);
        //    statusLayout.Controls.Add(lblCurrentStatusDuration, 0, 1);

        //    mainLayout.Controls.Add(topPanel, 0, 0);
        //    mainLayout.Controls.Add(statusLayout, 0, 1); // 状态面板（含状态标签和持续时间）

        //    this.Controls.Add(mainLayout);
        //    AdjustFontSizes();
        //}

        //// 创建时间标签的辅助方法
        //private Label CreateTimeLabel(string text)
        //{
        //    return new Label
        //    {
        //        Text = text,
        //        Dock = DockStyle.Fill,
        //        TextAlign = ContentAlignment.MiddleCenter,
        //        AutoSize = false,
        //        Margin = new Padding(2),
        //        Padding = new Padding(0)
        //    };
        //}

        //// 响应式字体调整
        //private void MainForm_Resize(object sender, EventArgs e)
        //{
        //    AdjustFontSizes();
        //}

        //// 动态调整字体大小
        //private void AdjustFontSizes()
        //{
        //    //// 时间标签字体 = 顶部面板高度的35%
        //    //float timeFontSize = topPanel.Height * 0.5f;
        //    //timeFontSize = Math.Min(timeFontSize, 50); // 设置最大限制

        //    //// 状态标签字体 = 状态面板高度的30%
        //    //float statusFontSize = statusPanel.Height * 0.5f;
        //    //statusFontSize = Math.Min(statusFontSize, 400); // 设置最大限制

        //    //// 应用字体大小
        //    //lblRunningTime.Font = new System.Drawing.Font("Arial", timeFontSize, FontStyle.Bold);
        //    //lblStopTime.Font = new System.Drawing.Font("Arial", timeFontSize, FontStyle.Bold);
        //    //lblAlarmTime.Font = new System.Drawing.Font("Arial", timeFontSize, FontStyle.Bold);
        //    //lblStatus.Font = new System.Drawing.Font("Arial", statusFontSize, FontStyle.Bold);


        //    // 时间标签字体 = 顶部面板高度的40%
        //    float timeFontSize = topPanel.Height * 0.4f;
        //    timeFontSize = Math.Min(timeFontSize, 50);

        //    // 状态标签字体 = 状态面板高度 * 70% * 0.5f
        //    float statusFontSize = (this.Height * 0.85f * 0.7f) * 0.5f;
        //    statusFontSize = Math.Min(statusFontSize, 300);

        //    //// 持续时间标签字体 = 状态标签字体的70%
        //    //float durationFontSize = statusFontSize * 0.4f;
        //    // 持续时间字体 = 状态区域高度的15%（持续时间部分）
        //    float durationFontSize = (this.Height * 0.85f) * 0.15f;
        //    durationFontSize = Math.Min(durationFontSize, 300);

        //    lblRunningTime.Font = new System.Drawing.Font("Arial", timeFontSize, FontStyle.Bold);
        //    lblStopTime.Font = new System.Drawing.Font("Arial", timeFontSize, FontStyle.Bold);
        //    lblAlarmTime.Font = new System.Drawing.Font("Arial", timeFontSize, FontStyle.Bold);

        //    // 状态标签和持续时间标签使用相同的字体设置
        //    lblStatus.Font = new System.Drawing.Font("Arial", statusFontSize, FontStyle.Bold);
        //    lblCurrentStatusDuration.Font = new System.Drawing.Font("Arial", durationFontSize, FontStyle.Bold);

        //    // 应用相同的颜色
        //    lblCurrentStatusDuration.ForeColor = lblStatus.ForeColor;
        //    //if (lblCurrentStatusDuration != null)
        //    //{
        //    //    lblCurrentStatusDuration.Font = new Font("Arial", durationFontSize, FontStyle.Bold);
        //    //}
        //}

        //private void timer1_Tick(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        //OperateResult result = plcClient.ConnectServer();
        //        //if (!result.IsSuccess)
        //        //{
        //        //    throw new Exception($"PLC连接失败: {result.Message}\n" +
        //        //                       $"IP: {plcIp}, 端口: {plcPort}");
        //        //}
        //        //// 读取三个点位的值
        //        //int[] statusValues = new int[3];
        //        //for (int i = 0; i < 3; i++)
        //        //{
        //        //    statusValues[i] = ReadDeviceValue(deviceAddresses[i]);
        //        //}
        //        // 1. 检查班次变化
        //        if (CheckShiftChange())
        //        {
        //            // 班次变化时保存数据并重置时间
        //            SaveStatusToDatabase(previousShift.ToString());
        //            ResetAllTimes();
        //        }
        //        //读一个点位
        //        int statusValues = ReadDeviceValue(dataAddress);
        //        // 解析设备状态
        //        DeviceStatus newStatus = DetermineStatus(statusValues);

        //        // 更新状态
        //        UpdateStatus(newStatus);

        //        // 更新时间显示
        //        UpdateTimeDisplays();

        //        // 5. 更新当前状态持续时间
        //        TimeSpan currentDuration = DateTime.Now - currentStatusStartTime;
        //        lblCurrentStatusDuration.Text = $"{FormatTimeSpan(currentDuration)}";
        //    }
        //    catch (Exception ex)
        //    {
        //        UpdateStatus(DeviceStatus.Error);
        //        lblStatus.Text = $"当前状态：错误 ({ex.Message})";
        //        lblCurrentStatusDuration.Text = "通信错误";
        //        this.BackColor = Color.Gray;
        //    }
        //}

        //private int ReadDeviceValue(string address)
        //{
        //    // 使用ReadInt32方法读取点位值
        //    OperateResult<short> readResult = plcClient.ReadInt16(address);

        //    if (readResult.IsSuccess)
        //    {
        //        // 设置存储路径
        //        string directoryPath = @"D:\日志记录"; // 替换为你的实际路径
        //        string filePath = Path.Combine(directoryPath, $"ReadData_{DateTime.Now:yyyyMMdd}.txt");
        //        if (!Directory.Exists(directoryPath))
        //        {
        //            Directory.CreateDirectory(directoryPath);
        //        }
        //        // 追加内容到文件（自动换行）
        //        File.AppendAllText(filePath, "读取数:" + readResult.Content + Environment.NewLine);
        //        return readResult.Content;


        //    }
        //    else
        //    {
        //        throw new Exception($"读取点位{address}失败: {readResult.Message}");
        //    }
        //}

        //private DeviceStatus DetermineStatus(int values)
        //{
        //    //// 检查是否为单一状态
        //    //if (values[0] == 1 && values[1] == 0 && values[2] == 0)
        //    //    return DeviceStatus.Running;
        //    //if (values[0] == 0 && values[1] == 1 && values[2] == 0)
        //    //    return DeviceStatus.Alarm;
        //    //if (values[0] == 0 && values[1] == 0 && values[2] == 1)
        //    //    return DeviceStatus.Stop;

        //    //// 处理异常状态
        //    //if (values[0] == 1 && values[1] == 1)
        //    //    throw new Exception("运行和报警同时激活");
        //    //if (values[0] == 1 && values[2] == 1)
        //    //    throw new Exception("运行和停机同时激活");
        //    //if (values[1] == 1 && values[2] == 1)
        //    //    throw new Exception("报警和停机同时激活");
        //    //if (values.All(v => v == 1))
        //    //    throw new Exception("所有状态同时激活");
        //    //if (values.All(v => v == 0))
        //    //    throw new Exception("所有状态都未激活");

        //    //return DeviceStatus.Stop; // 默认停机状态

        //    if (values == 1)
        //        return DeviceStatus.Running;
        //    if (values == 3)
        //        return DeviceStatus.Alarm;
        //    if (values == 0)
        //        return DeviceStatus.Stop;
        //    if (values != 0 && values != 1 && values != 3)
        //        throw new Exception($"读取{dataAddress}点位值为{values}");
        //    return DeviceStatus.Error; // 默认停机状态
        //}

        //private void UpdateStatus(DeviceStatus newStatus)
        //{
        //    // 计算上一个状态的持续时间
        //    TimeSpan duration = DateTime.Now - lastUpdateTime;

        //    // 更新累计时间
        //    switch (currentStatus)
        //    {
        //        case DeviceStatus.Running:
        //            runningTime += duration;
        //            break;
        //        case DeviceStatus.Alarm:
        //            alarmTime += duration;
        //            break;
        //        case DeviceStatus.Stop:
        //            stopTime += duration;
        //            break;
        //    }
        //    // 状态变化时保存数据
        //    if (currentStatus != newStatus && currentStatus != DeviceStatus.Error)
        //    {
        //        SaveStatusToDatabase();
        //    }
        //    //// 更新当前状态
        //    //if (currentStatus != newStatus)
        //    //{
        //    //    currentStatus = newStatus;
        //    //    currentStatusStartTime = DateTime.Now;
        //    //}
        //    // 更新当前状态
        //    currentStatus = newStatus;
        //    lastUpdateTime = DateTime.Now;

        //    // 更新UI
        //    switch (newStatus)
        //    {
        //        case DeviceStatus.Running:
        //            this.BackColor = Color.LimeGreen;
        //            lblStatus.Text = "运行";
        //            break;
        //        case DeviceStatus.Alarm:
        //            this.BackColor = Color.Red;
        //            lblStatus.Text = "报警";
        //            break;
        //        case DeviceStatus.Stop:
        //            this.BackColor = Color.Yellow;
        //            lblStatus.Text = "停机";
        //            break;
        //        case DeviceStatus.Error:
        //            this.BackColor = Color.Gray;
        //            lblStatus.Text = "当前状态：通信错误";
        //            break;
        //    }
        //}

        //private void UpdateTimeDisplays()
        //{
        //    lblRunningTime.Text = $"运行时长: {FormatTimeSpan(runningTime)}";
        //    lblAlarmTime.Text = $"报警时长: {FormatTimeSpan(alarmTime)}";
        //    lblStopTime.Text = $"停机时长: {FormatTimeSpan(stopTime)}";
        //}

        //private string FormatTimeSpan(TimeSpan ts)
        //{
        //    return $"{ts.Hours:D2}:{ts.Minutes:D2}:{ts.Seconds:D2}";
        //}

        //// 清理资源
        //protected override void OnFormClosing(FormClosingEventArgs e)
        //{
        //    base.OnFormClosing(e);
        //    timer1?.Stop();
        //    plcClient?.Dispose();
        //}
        //public Form1()
        //{
        //    InitializeComponent();
        //}


        //// 班次显示转换方法（兼容低版本）
        //private string GetShiftDisplayName(ShiftType shift)
        //{
        //    switch (shift)
        //    {
        //        case ShiftType.DayShift:
        //            return "白班";
        //        case ShiftType.NightShift:
        //            return "晚班";
        //        default:
        //            return "未知";
        //    }
        //}
        //// 保存数据到数据库
        //private void SaveStatusToDatabase(string shiftType = "")
        //{
        //    try
        //    {
        //        MachineStatusMessage data = new MachineStatusMessage
        //        {
        //            MachineId = "TB07", // 根据需要设置
        //            RunningTime = FormatTimeSpan(runningTime),
        //            AlarmTime = FormatTimeSpan(alarmTime),
        //            StopTime = FormatTimeSpan(stopTime),
        //            AlarmMessage = "",//目前为空，后续添加
        //            TeamGroup = !string.IsNullOrEmpty(shiftType)
        //            ? GetShiftDisplayName((ShiftType)Enum.Parse(typeof(ShiftType), shiftType))
        //            : GetShiftDisplayName(currentShift),
        //            //TeamGroup = "",
        //            GetTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
        //        };

        //        bts.InsertMachineStatusTime(data);
        //    }
        //    catch (Exception ex)
        //    {
        //        Console.WriteLine($"保存数据失败: {ex.Message}");
        //    }
        //}


    }
}
